//
//  CustomYearDatePicker.m
//  基本框架
//
//  Created by runone02 on 2018/7/24.
//  Copyright © 2018年 liqiyun. All rights reserved.
//

#import "CustomYearDatePicker.h"

@interface CustomYearDatePicker ()
/**年份 */
@property (nonatomic, strong) NSMutableArray *yearArray;
/**选择器 */
@property (nonatomic, strong) UIPickerView *pickerView;
@end
@implementation CustomYearDatePicker

@synthesize year;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.pickerView = [[UIPickerView alloc] initWithFrame:self.bounds];
        
        self.pickerView.delegate  = self;
        self.pickerView.dataSource = self;
        self.pickerView.showsSelectionIndicator = YES;
        [self addSubview:self.pickerView];
        
        
        self.yearArray = [[NSMutableArray alloc] initWithCapacity:0];
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy"];
        //年份
        year = [[formatter stringFromDate:date] intValue];
        for (int i = year-30; i<year+30; i++) {
            NSString *str = [NSString stringWithFormat:@"%d",i];
            NSLog(@"%@",str);
            [self.yearArray addObject:str];
            
        }
        [self.pickerView selectRow:30 inComponent:0 animated:YES];
    }
    return self;
}
#pragma mark - pickerview
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.yearArray.count;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.frame = CGRectMake(0, 0, self.frame.size.width/2.0, 50);
    [label setFont:[UIFont boldSystemFontOfSize:16]];
    label.text = [NSString stringWithFormat:@"%@",[self.yearArray objectAtIndex:row]];
    return label;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return self.frame.size.width;
}

//选中
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        int rowy = (int)[self.pickerView selectedRowInComponent:0];
        year = [[self.yearArray objectAtIndex:rowy] intValue];
    }
}


@end
